package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.DianZanPersonAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.DivisionObject;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.SearchBarView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/10/31.
 * 点赞对象 一级页面
 */

public class DianZanPersonActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private TextView tip;
    private Button callBack;
    private RecyclerView recyclerView;
    private SmartRefreshLayout mSmartRefreshLayout;


    private DianZanPersonAdapter adapter;
    private DianZanPersonAdapter sadapter;
    private List<DivisionObject> divisions = new ArrayList<>();
    private List<UserObject> users = new ArrayList<>();
    private List<UserObject> searchUsers = new ArrayList<>();
    private SearchBarView searchBarView;
    private String keyWord = "";
    private String departId;
    private String type = "1";//类型 1：点赞 2：被赞
    private UserObject selectPerson;

    private RelativeLayout emptyLayout;
    private TextView emptyText;
    private RelativeLayout emptyLayout2;
    private String exUserId;//企业的userId

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, DianZanPersonActivity.class);
        activity.startActivity(intent);
    }

    public static void jump(Fragment fragment, int requscode) {
        Intent intent = new Intent(fragment.getActivity(), DianZanPersonActivity.class);
        fragment.startActivityForResult(intent, requscode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dianzan_reason);
        adapter = new DianZanPersonAdapter(this, divisions, users);
        sadapter = new DianZanPersonAdapter(this, null, searchUsers);
        exUserId = SharedPreferencesUtils.getExcitationUserId(DianZanPersonActivity.this);
        initView();
        setSmartRefreshLayout();
    }

    private void initView() {
        tip = findViewById(R.id.tip);
        emptyLayout = findViewById(R.id.empty_layout1);
        emptyText = findViewById(R.id.tip_text);
        emptyLayout2 = findViewById(R.id.empty_layout2);
        title = findViewById(R.id.title_text_title);
        mSmartRefreshLayout = findViewById(R.id.refreshlayout);
        emptyLayout.setVisibility(View.GONE);
        title.setText("点赞对象");
        tip.setText("您想为谁点赞？");
        callBack = findViewById(R.id.title_left_button);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        searchBarView = findViewById(R.id.searBarView);
        setListener();
    }

    private void setSmartRefreshLayout() {
        mSmartRefreshLayout.autoRefresh(0, 1, 0.62f);
        mSmartRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        mSmartRefreshLayout.setEnableLoadmore(false);//将不会触发加载更多事件,不需要加载更多功能设置

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (TextUtils.isEmpty(keyWord)) {
                    users.clear();
                    divisions.clear();
                    adapter.notifyDataSetChanged();
                    getDianzanPerson();
                } else {
                    searchUsers.clear();
                    sadapter.notifyDataSetChanged();
                    searchDianzanPerson();
                }
            }
        });

        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
            }
        });
    }

    private void setListener() {

        callBack.setOnClickListener(this);
        searchBarView.setOnSearchClicListener(new SearchBarView.Onclick() {
            @Override
            public void onSearchClick(EditText ed, String text) {
                keyWord = text;
                searchUsers.clear();
                recyclerView.setAdapter(sadapter);
                searchDianzanPerson();
            }

            @Override
            public void onCanclClick() {
                keyWord = "";
                adapterNotify();
            }
        });

        adapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {

                if (position < divisions.size()) {//选择部门
                    departId = divisions.get(position).getDeptId();
                    SelectPersonActivity.jump(DianZanPersonActivity.this, departId, Globals.REQUSE_CODE_SelectPersonActivity);
                } else {//选择用户
                    selectPerson = users.get(position - divisions.size());
                    if (exUserId.equals(selectPerson.getUserId())) {
                        toast("不能点赞自己！");
                        return;
                    }
                    finishThis();
                }

            }
        });
        sadapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                selectPerson = searchUsers.get(position);
                if (exUserId.equals(selectPerson.getUserId())) {
                    toast("不能点赞自己！");
                    return;
                }
                finishThis();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }

    private void searchDianzanPerson() {
        Log.e("搜索", keyWord);
        HttpExcitation.searchDianZanPerson(Globals.getToken(), keyWord, searchResponseHandler);
    }

    AsyncHttpResponseHandler searchResponseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            Log.e("搜索点赞对象", result);
            mSmartRefreshLayout.finishRefresh();
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    searchUsers.clear();
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONObject info = infoArray.optJSONObject(i);
                        UserObject userObject = new UserObject();
                        userObject.setComId(info.optString("comId"));
                        userObject.setEmpName(info.optString("userName"));
                        userObject.setUserId(info.optString("userId"));
                        userObject.setAvatarPath(info.optString("avatarPath"));
                        searchUsers.add(userObject);
                    }
                    adapterNotify();
                } else {
                    emptyLayout2.setVisibility(View.VISIBLE);
                    emptyLayout.setVisibility(View.GONE);
                    emptyText.setText("搜索失败！");
                    toast(json.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                emptyLayout2.setVisibility(View.VISIBLE);
                emptyLayout.setVisibility(View.GONE);
                emptyText.setText("搜索失败！");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            mSmartRefreshLayout.finishRefresh();
            emptyLayout2.setVisibility(View.VISIBLE);
            emptyLayout.setVisibility(View.GONE);
            emptyText.setText("搜索失败！");
        }
    };

    /**
     * 获取点赞对象和组织
     */
    private void getDianzanPerson() {
        departId = null;
        HttpExcitation.searchOrganization(Globals.getToken(), departId, getResponseHandler);
    }

    AsyncHttpResponseHandler getResponseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            mSmartRefreshLayout.finishRefresh();
            String result = new String(responseBody);
            Log.e("获取点赞对象", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONArray infoArray0 = infoArray.optJSONArray(i);
                        if (i == 0) {
                            divisions.clear();
                            for (int j = 0; j < infoArray0.length(); j++) {
                                JSONObject info = infoArray0.optJSONObject(j);
                                DivisionObject divisionObject = new DivisionObject();
                                divisionObject.setComId(info.optString("comId"));
                                divisionObject.setDeptId(info.optString("deptId"));
                                divisionObject.setDeptName(info.optString("deptName"));
                                divisions.add(divisionObject);
                            }
                        } else if (i == 1) {
                            users.clear();
                            for (int j = 0; j < infoArray0.length(); j++) {
                                JSONObject info = infoArray0.optJSONObject(j);
                                UserObject userObject = new UserObject();
                                userObject.setComId(info.optString("comId"));
                                userObject.setEmpName(info.optString("empName"));
                                userObject.setUserId(info.optString("userId"));
                                userObject.setAvatarPath(info.optString("avatarPath"));
                                users.add(userObject);
                            }
                        }
                    }
                    adapterNotify();
                } else {
                    toast(json.optString("msg"));
                    emptyLayout.setVisibility(View.VISIBLE);
                    emptyLayout2.setVisibility(View.GONE);
                    emptyText.setText("加载失败！");
                }
            } catch (JSONException e) {
                mSmartRefreshLayout.finishRefresh();
                e.printStackTrace();
                emptyLayout.setVisibility(View.VISIBLE);
                emptyLayout2.setVisibility(View.GONE);
                emptyText.setText("没有部门和成员！");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            mSmartRefreshLayout.finishRefresh();
            emptyLayout2.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.VISIBLE);
            emptyText.setText("没有部门和成员！");

        }
    };

    private void finishThis() {
        Intent intent = new Intent();
        intent.putExtra("diazanPerson", selectPerson);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void adapterNotify() {
        if (TextUtils.isEmpty(keyWord)) {
            Log.e("users", users.size() + "");
            if ((users.size() + divisions.size()) == 0) {
                emptyLayout.setVisibility(View.VISIBLE);
                emptyLayout2.setVisibility(View.GONE);
                emptyText.setText("什么都没有哦~");
            } else {
                emptyLayout.setVisibility(View.GONE);
                emptyLayout2.setVisibility(View.GONE);
            }
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        } else {
            Log.e("searchUsers", searchUsers.size() + "");
            if (searchUsers.size() == 0) {
                emptyLayout.setVisibility(View.GONE);
                emptyLayout2.setVisibility(View.VISIBLE);
                emptyText.setText("什么都没有哦~");
            } else {
                emptyLayout2.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.GONE);
            }
            recyclerView.setAdapter(sadapter);
            sadapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Globals.REQUSE_CODE_SelectPersonActivity:
                    selectPerson = (UserObject) data.getSerializableExtra("diazanPerson");
                    finishThis();
                    break;
            }
        }
    }
}
